package com.xuxin.nantai.activity.quan;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.king.zxing.Intents;
import com.xuxin.nantai.R;
import com.xuxin.nantai.activity.MyCaptureActivity;
import com.xuxin.nantai.base.BaseActivity;
import com.xuxin.nantai.base.BaseConstant;
import com.xuxin.nantai.base.BaseTextWatcher;
import com.xuxin.nantai.bean.AllAreaBean;
import com.xuxin.nantai.bean.BaseBean;
import com.xuxin.nantai.bean.DefaultGroupBean;
import com.xuxin.nantai.bean.FlowingCodeBean;
import com.xuxin.nantai.bean.GroupBean;
import com.xuxin.nantai.bean.HangUpdateLoginBean;
import com.xuxin.nantai.bean.InspectorBean;
import com.xuxin.nantai.contract.AllAreaContract;
import com.xuxin.nantai.contract.CompleteUpdateContract;
import com.xuxin.nantai.presenter.AllAreaPresenter;
import com.xuxin.nantai.presenter.CompleteUpdatePresenter;
import com.xuxin.nantai.utils.ACache;
import com.xuxin.nantai.utils.FlowingUtils;
import com.xuxin.nantai.utils.TimeUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xu_xin
 * Created on 2020.06.08 0008
 * 缝制全检新增修改
 */
public class CompleteUpdateActivity extends BaseActivity implements CompleteUpdateContract.View, AllAreaContract.View {
    private CompleteUpdateContract.Presenter presenter = new CompleteUpdatePresenter(this);
    private AllAreaContract.Presenter presenter2 = new AllAreaPresenter(this);
    @BindView(R.id.title_left)
    ImageView title_left;
    @BindView(R.id.title_right)
    ImageView title_right;
    @BindView(R.id.title_name)
    TextView title_name;

    @BindView(R.id.complete_update_team)
    TextView complete_update_team;//组检/单检
    @BindView(R.id.complete_update_reCheck)
    CheckBox complete_update_reCheck;//是否复检
    @BindView(R.id.complete_update_flowing)
    EditText complete_update_flowing;//流转单号
    @BindView(R.id.complete_update_name)
    TextView complete_update_name;//成品名称
    @BindView(R.id.complete_update_pack)
    TextView complete_update_pack;//本包数
    @BindView(R.id.complete_update_com)
    EditText complete_update_com;//部件数
    @BindView(R.id.complete_update_check)
    TextView complete_update_check;//全检数
    @BindView(R.id.complete_update_area)
    TextView complete_update_area;//厂区
    @BindView(R.id.complete_update_inspector)
    TextView complete_update_inspector;//检验员
    @BindView(R.id.complete_update_time)
    TextView complete_update_time;//检验日期
    @BindView(R.id.complete_update_group)
    TextView complete_update_group;//生产组别

    private String Guid;//唯一Guid
    private String ID;//唯一ID
    private String cInvCode;//成品编码
    private String cInvName;//成品名称
    private String PackQty;//本包数
    private String ComNum;//部件数
    private String CheckNum;//全检数
    private String InspectorCode;//检验员代码
    private String InspectorName;//检验员姓名
    private String InspectTime;//检验日期
    private String FacArea;//厂区
    private String TeamType;//单检或组检
    private int IsReCheck;//是否复检1,0
    private String FlowingCode;//流转单号
    private String GroupName;//生产组别名称
    private String GroupCode;//生产组别代码

    private MaterialDialog materialDialog;//检验员
    private MaterialDialog commitDialog;

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_complete_update);
    }

    @Override
    public void initView() {
        Bundle bundle = getIntent().getExtras();
        if (null != bundle && !StringUtils.isEmpty(bundle.getString("Guid"))) {
            //修改
            title_name.setText("缝制全检修改");
            Guid = bundle.getString("Guid");
            ID = bundle.getString("ID");
            cInvCode = bundle.getString("cInvCode");
            cInvName = bundle.getString("cInvName");
            PackQty = bundle.getString("PackQty");
            ComNum = bundle.getString("ComNum");
            CheckNum = bundle.getString("CheckNum");
            InspectorCode = bundle.getString("InspectorCode");
            InspectorName = bundle.getString("InspectorName");
            InspectTime = bundle.getString("InspectTime");
            FacArea = bundle.getString("FacArea");
            TeamType = bundle.getString("TeamType");
            IsReCheck = bundle.getInt("IsReCheck");
            FlowingCode = bundle.getString("FlowingCode");
            GroupName = bundle.getString("GroupName");
            GroupCode = bundle.getString("GroupCode");

            LogUtils.e("Guid = " + Guid);
            LogUtils.e("ID = " + ID);
            LogUtils.e("cInvCode = " + cInvCode);
            LogUtils.e("cInvName = " + cInvName);
            LogUtils.e("PackQty = " + PackQty);
            LogUtils.e("ComNum = " + ComNum);
            LogUtils.e("CheckNum = " + CheckNum);
            LogUtils.e("InspectorCode = " + InspectorCode);
            LogUtils.e("InspectorName = " + InspectorName);
            LogUtils.e("InspectTime " + InspectTime);
            LogUtils.e("FacArea " + FacArea);
            LogUtils.e("TeamType " + TeamType);
            LogUtils.e("IsReCheck " + IsReCheck);
            LogUtils.e("FlowingCode " + FlowingCode);
            LogUtils.e("--------------------------");
            complete_update_team.setText(TeamType);
            complete_update_reCheck.setChecked(1 == IsReCheck);
            complete_update_flowing.setText(FlowingCode);
            complete_update_name.setText(cInvName);
            complete_update_pack.setText(String.valueOf(PackQty));
            complete_update_com.setText(String.valueOf(ComNum));
            complete_update_check.setText(String.valueOf(CheckNum));
            complete_update_area.setText(FacArea);
            complete_update_inspector.setText(InspectorName);
            complete_update_time.setText(InspectTime);
            complete_update_group.setText(GroupName);
            complete_update_com.addTextChangedListener(new myTextWatcher());
            LogUtils.e("缝制全检修改_Guid = " + Guid);
        } else {
            //新增
            title_name.setText("缝制全检新增");
            LogUtils.e("缝制全检新增_Guid = " + Guid);
        }
        //流转单输入监控
        complete_update_flowing.addTextChangedListener(new BaseTextWatcher() {
            @Override
            public void onTextChanged(String message) {
                cInvName = null;
                cInvCode = null;
                PackQty = null;
                ComNum = null;
                CheckNum = null;
                complete_update_name.setText("");
                complete_update_pack.setText("");
                complete_update_com.setText("");
                complete_update_check.setText("");
            }
        });
        //新增
        if (StringUtils.isEmpty(Guid)) {
            //默认日期今天
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
            Date date = new Date(System.currentTimeMillis());
            InspectTime = simpleDateFormat.format(date);
            complete_update_time.setText(InspectTime);
        }
    }

    @Override
    public void initData() {
        handler.sendEmptyMessage(0); //根据单检组检获取检验员
        handler.sendEmptyMessage(1);  //获取所有生产组别
        handler.sendEmptyMessage(4);//获取厂区列表
        if (StringUtils.isEmpty(Guid)) {
            //新增
            handler.sendEmptyMessage(2);//获取默认生产组别
            handler.sendEmptyMessage(6);//获取默认厂
        }
    }

    @Override
    public void onComplete() {
        if (null != commitDialog) {
            commitDialog.dismiss();
        }
    }

    @Override
    @OnClick({R.id.title_left, R.id.complete_update_team, R.id.complete_update_inspector,
            R.id.complete_update_search, R.id.complete_update_scan, R.id.complete_update_time,
            R.id.complete_update_group, R.id.complete_update_update, R.id.complete_update_area})
    public void onClick(View view) {
        KeyboardUtils.hideSoftInput(this);
        switch (view.getId()) {
            case R.id.title_left:
                finish();
                break;
            case R.id.complete_update_team:
                new MaterialDialog.Builder(this)
                        .items("组检", "单检")
                        .itemsCallback((dialog, view1, position, text) -> {
                            try {
                                TeamType = (position == 0 ? "组检" : "单检");
                                complete_update_team.setText(TeamType);
                                InspectorName = null;
                                InspectorCode = null;
                                complete_update_inspector.setText("");
                                handler.sendEmptyMessage(0); //根据单检组检获取检验员
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        })
                        .show();
                break;
            case R.id.complete_update_inspector:
                try {
                    String team = complete_update_team.getText().toString();
                    if ("单检".equals(team)) {
                        return;
                    }
                    if (null != inspectorBean) {
                        if (null == materialDialog) {
                            List<Integer> list = new ArrayList<>();
                            for (int i = 0; i < inspectorBean.getTeam().size(); i++) {
                                if (inspectorBean.getTeam().get(i).isIsCheck()) {
                                    list.add(i);
                                }
                            }
                            Integer[] strings = new Integer[list.size()];
                            Integer[] selectedIndices = (StringUtils.isEmpty(Guid)) ? list.toArray(strings) : null;
                            LogUtils.e("selectedIndices = " + (null == selectedIndices));
                            materialDialog = new MaterialDialog.Builder(this)
                                    .title("请选择检验员")
                                    .positiveText("确认")
                                    .items(inspectorBean.getTeam())
                                    .itemsCallbackMultiChoice(selectedIndices, new myCallback())
                                    .show();
                        } else {
                            materialDialog.show();
                        }
                        LogUtils.e("开始for循环");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.complete_update_search:
                FlowingCode = complete_update_flowing.getText().toString();
                if (StringUtils.isEmpty(FlowingCode)) {
                    ToastUtils.showShort("请填写流转单号");
                } else {
                    handler.sendEmptyMessage(3); //根据流转单获取数据
                }
                break;
            case R.id.complete_update_scan:
                startActivityForResult(new Intent(this, MyCaptureActivity.class), BaseConstant.result_scan);
                break;
            case R.id.complete_update_time:
                TimeUtils.showDate(this, new TimeUtils.onListener() {
                    @Override
                    public void onShow(String time) {
                        complete_update_time.setText(time);
                    }
                });
                break;
            case R.id.complete_update_group:
                if (null != groupBean) {
                    new MaterialDialog.Builder(this)
                            .title("请选择生产组别")
                            .items(groupBean.getData())
                            .itemsCallback((dialog, view1, position, text) -> {
                                try {
                                    GroupName = groupBean.getData().get(position).getCDepName();
                                    GroupCode = groupBean.getData().get(position).getCDepCode();
                                    complete_update_group.setText(GroupName);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            })
                            .show();
                }
                break;
            case R.id.complete_update_update:
                //修改缝制全检
                try {
                    PackQty = complete_update_pack.getText().toString();
                    ComNum = complete_update_com.getText().toString();
                    CheckNum = complete_update_check.getText().toString();
                    TeamType = complete_update_team.getText().toString();
                    IsReCheck = complete_update_reCheck.isChecked() ? 1 : 0;
                    FlowingCode = complete_update_flowing.getText().toString();
                    cInvName = complete_update_name.getText().toString();
                    FacArea = complete_update_area.getText().toString();
                    InspectorName = complete_update_inspector.getText().toString();
                    InspectTime = complete_update_time.getText().toString();
                    GroupName = complete_update_group.getText().toString();
                    if (StringUtils.isEmpty(TeamType)) {
                        ToastUtils.showShort("请选择单检或组检");
                        return;
                    }
                    if (StringUtils.isEmpty(FlowingCode)) {
                        ToastUtils.showShort("请输入流转单号");
                        return;
                    }
                    if (StringUtils.isEmpty(cInvName)) {
                        ToastUtils.showShort("成品名称不能为空");
                        return;
                    }
                    if (StringUtils.isEmpty(PackQty)) {
                        ToastUtils.showShort("本包数不能为空");
                        return;
                    }
                    if (StringUtils.isEmpty(ComNum)) {
                        ToastUtils.showShort("部件数不能为空");
                        return;
                    }
                    if (StringUtils.isEmpty(CheckNum)) {
                        ToastUtils.showShort("全检数不能为空");
                        return;
                    }
                    if (StringUtils.isEmpty(FacArea)) {
                        ToastUtils.showShort("请输入厂区");
                        return;
                    }
                    if (StringUtils.isEmpty(InspectorName)) {
                        ToastUtils.showShort("请选择检验员");
                        return;
                    }
                    if (StringUtils.isEmpty(InspectTime)) {
                        ToastUtils.showShort("请选择检验日期");
                        return;
                    }
                    if (StringUtils.isEmpty(GroupName)) {
                        ToastUtils.showShort("请选择生产组别");
                        return;
                    }
                    commitDialog = new MaterialDialog.Builder(this)
                            .content("提交数据中...")
                            .progress(true, 0)
                            .cancelable(false)
                            .show();
                    handler.sendEmptyMessage(5);//修改保存
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.complete_update_area:
                if (null != allAreaBean && null != allAreaBean.getData() && allAreaBean.getData().size() > 0) {
                    new MaterialDialog.Builder(this)
                            .items(allAreaBean.getData())
                            .itemsCallback((dialog, view1, position, text) -> {
                                complete_update_area.setText(allAreaBean.getData().get(position).getItemName());
                            })
                            .show();
                }
                break;
        }
    }

    private Handler handler = new Handler(message -> {
        String LoginName = ACache.get(this).getAsString("LoginName");
        String UserName = ACache.get(this).getAsString("UserName");
        LogUtils.e("message.what = " + message.what);
        switch (message.what) {
            case 6://获取默认厂区
                presenter2.getDefaultArea(LoginName);
                break;
            case 0:
                //根据单检组检获取检验员
                String teamType = complete_update_team.getText().toString();
                presenter.getInspector(LoginName, teamType);
                break;
            case 1:
                //获取所有生产组别
                presenter.getGroups();
                break;
            case 2:
                //获取默认生产组别
                presenter.getDefaultGroup(LoginName);
                break;
            case 3:
                //根据流转单获取数据
                presenter.getFlowingCode(FlowingCode);
                break;
            case 4://获取厂区列表
                presenter2.getAllArea();
                break;
            case 5:
                //修改保存
                LogUtils.e("LoginName = " + LoginName);
                LogUtils.e("UserName = " + UserName);
                LogUtils.e("Guid = " + Guid);
                LogUtils.e("ID = " + ID);
                LogUtils.e("cInvCode = " + cInvCode);
                LogUtils.e("cInvName = " + cInvName);
                LogUtils.e("PackQty = " + PackQty);
                LogUtils.e("ComNum = " + ComNum);
                LogUtils.e("CheckNum = " + CheckNum);
                LogUtils.e("InspectorCode = " + InspectorCode);
                LogUtils.e("InspectorName = " + InspectorName);
                LogUtils.e("InspectTime = " + InspectTime);
                LogUtils.e("FacArea = " + FacArea);
                LogUtils.e("TeamType = " + TeamType);
                LogUtils.e("IsReCheck = " + IsReCheck);
                LogUtils.e("FlowingCode = " + FlowingCode);
                LogUtils.e("FlowingCode = " + FlowingCode);
                LogUtils.e("GroupName = " + GroupName);
                LogUtils.e("GroupCode = " + GroupCode);
                presenter.update(LoginName,
                        UserName,
                        Guid,
                        ID,
                        cInvCode,
                        cInvName,
                        PackQty,
                        ComNum,
                        CheckNum,
                        InspectorCode,
                        InspectorName,
                        InspectTime,
                        FacArea,
                        TeamType,
                        IsReCheck,
                        FlowingCode,
                        GroupName,
                        GroupCode);
                break;

        }
        return false;
    });

    private InspectorBean inspectorBean;

    @Override
    public void onSuccess(InspectorBean inspectorBean) {
        this.inspectorBean = inspectorBean;
        String inspector = complete_update_inspector.getText().toString();
        if (StringUtils.isEmpty(inspector) && inspectorBean.getTeam().size() > 0) {
            LogUtils.e("检验员为空，根据接口选择");
            StringBuilder sb_name = new StringBuilder();
            StringBuilder sb_code = new StringBuilder();
            for (int i = 0; i < inspectorBean.getTeam().size(); i++) {
                if (inspectorBean.getTeam().get(i).isIsCheck()) {
                    if (!StringUtils.isEmpty(sb_name)) {
                        sb_name.append(",");
                        sb_code.append(",");
                    }
                    sb_name.append(inspectorBean.getTeam().get(i).getTeamName());
                    sb_code.append(inspectorBean.getTeam().get(i).getTeamCode());
                }
            }
            LogUtils.e("sb_name = " + sb_name);
            LogUtils.e("sb_code = " + sb_code);
            InspectorName = sb_name.toString();
            InspectorCode = sb_code.toString();
            complete_update_inspector.setText(InspectorName);
        } else {
            LogUtils.e("已经有检验员，不赋值");
        }
    }

    @Override
    public void onSuccess(FlowingCodeBean flowingCodeBean) {
        cInvName = flowingCodeBean.getCInvName();
        cInvCode = flowingCodeBean.getCInvCode();
        PackQty = flowingCodeBean.getPackQty();
        ComNum = flowingCodeBean.getComNum();
        CheckNum = flowingCodeBean.getCheckNum();
        complete_update_com.setText(ComNum);//部件数
        complete_update_name.setText(cInvName);//成品名称
        complete_update_pack.setText(PackQty);//本包数
        complete_update_check.setText(CheckNum);//全检数
        complete_update_com.addTextChangedListener(new myTextWatcher());
    }

    private GroupBean groupBean;

    @Override
    public void onSuccess(GroupBean groupBean) {
        this.groupBean = groupBean;
    }

    @Override
    public void onSuccess(DefaultGroupBean defaultGroupBean) {
        if (null != defaultGroupBean) {
            GroupName = defaultGroupBean.getGroupName();
            GroupCode = defaultGroupBean.getGroupCode();
            complete_update_group.setText(GroupName);
        }
    }

    @Override
    public void onSuccess(BaseBean baseBean) {
        ToastUtils.showShort(baseBean.getMessage());
        setResult(BaseConstant.result_code);
        finish();
    }

    @Override
    public void onSuccess(HangUpdateLoginBean hangUpdateLoginBean) {
        try {
            FacArea = hangUpdateLoginBean.getData().get(0).getStaffArea();
            complete_update_area.setText(FacArea);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private AllAreaBean allAreaBean;

    @Override
    public void onSuccess(AllAreaBean allAreaBean) {
        this.allAreaBean = allAreaBean;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == BaseConstant.result_scan && null != data && null != data.getExtras()) {
            //处理扫描结果（在界面上显示）
            String result = FlowingUtils.getFlowing(data.getStringExtra(Intents.Scan.RESULT));
            if (StringUtils.isEmpty(result)) {
                ToastUtils.showShort("请填写流转单号");
            } else {
                LogUtils.e("result = " + result);
                FlowingCode = result;
                complete_update_flowing.setText(FlowingCode);
                handler.sendEmptyMessage(3); //根据流转单获取数据
            }
        }
    }

    /**
     * 部件数输入监控
     */
    private class myTextWatcher extends BaseTextWatcher {

        @Override
        public void onTextChanged(String message) {
            try {
                String pack = complete_update_pack.getText().toString();
                if (!StringUtils.isEmpty(pack) && !StringUtils.isEmpty(message)) {
                    LogUtils.e("本包数不为空，可以计算数值");
                    int PackQty_num = Integer.parseInt(PackQty);
                    int ComNum_num = Integer.parseInt(message);
                    int CheckNum_num = PackQty_num * ComNum_num;
                    complete_update_check.setText(String.valueOf(CheckNum_num));
                    LogUtils.e("计算数值 CheckNum_num = " + CheckNum_num);
                } else {
                    complete_update_check.setText("");
                    LogUtils.e("本包数或部件数为空，不计算数值");
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
                LogUtils.e("输入有误");
            }
        }
    }

    private class myCallback implements MaterialDialog.ListCallbackMultiChoice {

        @Override
        public boolean onSelection(MaterialDialog dialog, Integer[] position, CharSequence[] text) {
            try {
                StringBuilder sb_code = new StringBuilder();
                StringBuilder sb_name = new StringBuilder();
                for (int p : position) {
                    String code = inspectorBean.getTeam().get(p).getTeamCode();
                    String name = inspectorBean.getTeam().get(p).getTeamName();
                    if (sb_code.length() != 0) {
                        sb_code.append(",");
                        sb_name.append(",");
                    }
                    sb_code.append(code);
                    sb_name.append(name);
                    InspectorCode = sb_code.toString();
                    InspectorName = sb_name.toString();
                    complete_update_inspector.setText(InspectorName);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }
    }
}